<template>
    <div class="bug-detail-container">

        <!-- 标题区域 -->
        <div class="bug-title">
            <h3>{{ bugDetail.bugTitle }}</h3>
        </div>

        <!-- 基本信息 -->
        <div class="bug-info">
            <!-- 优先级和状态选择 -->
            <div class="flex flex-wrap gap-2 mb-3">
                <!-- 优先级选择 -->
                <div class="relative">
                    <el-tag :type="getPriorityType(bugDetail.bugLevel)" :style="{
                        backgroundColor: getBugLevelColor2(bugDetail.bugLevel),
                        color: getBugLevelTextColor2(bugDetail.bugLevel)
                    }" class="flex items-center cursor-pointer" @click="showPrioritySelect = !showPrioritySelect">
                        {{ getBugLevelName(bugDetail.bugLevel) }}
                        <el-icon class="ml-1">
                            <ArrowDown />
                        </el-icon>
                    </el-tag>
                    <div v-if="showPrioritySelect" class="priority-dropdown">
                        <div v-for="priority in PRIORITY_COLORS" :key="priority.value" class="dropdown-item"
                            @click="changePriority(bugDetail, priority.value)">
                            {{ priority.label }}
                        </div>
                    </div>
                </div>

                <!-- 状态选择 -->
                <div class="relative">
                    <el-tag :type="getBugStatusType(bugDetail.bugLevel)" :style="{
                        backgroundColor: getBugStatusColor(bugDetail.bugStatus),
                        color: '#fff'
                    }" class="flex items-center cursor-pointer" @click="showStatusSelect = !showStatusSelect">
                        {{ getBugStatusName(bugDetail.bugStatus) }}
                        <el-icon class="ml-1">
                            <ArrowDown />
                        </el-icon>
                    </el-tag>
                    <div v-if="showStatusSelect" class="status-dropdown">
                        <div v-for="status in bugStatusList" :key="status.bug_status" class="dropdown-item"
                            @click="changeStatus(bugDetail, status.bug_status)">
                            {{ status.bug_status_name }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 基本信息行 -->
            <div class="info-grid">
                <div class="info-item">
                    <span class="info-label">创建人：</span>
                    <span class="info-value">{{ bugDetail.createUserName }}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">创建时间：</span>
                    <span class="info-value">{{ formatDate(bugDetail.createTime) }}</span>
                </div>
                <div class="info-item">
                    <span class="info-label">Bug ID：</span>
                    <span class="info-value">{{ bugDetail.id }}</span>
                </div>
            </div>

            <!-- 修复人 -->
            <div class="assignee-container">
                <div class="assignee-label">修复人：</div>
                <div class="assignee-selector" @click="showAssigneeSelect = true">
                    <div class="avatar-group">
                        <div v-for="assignee in bugDetail.assignees" :key="assignee" class="avatar">
                            {{ assignee.charAt(0) }}
                        </div>
                    </div>
                    <div class="assignee-names">
                        <span v-if="bugDetail.assignees.length > 0">
                            {{ bugDetail.assignees.join(', ') }}
                        </span>
                        <span v-else class="placeholder">选择修复人</span>
                        <el-icon class="arrow-icon">
                            <ArrowDown />
                        </el-icon>
                    </div>
                </div>

                <!-- 修复人选择下拉框 -->
                <div v-if="showAssigneeSelect" class="assignee-dropdown">
                    <div class="search-box">
                        <el-icon class="search-icon">
                            <Search />
                        </el-icon>
                        <input v-model="assigneeSearchKeyword" placeholder="搜索处理人..." class="search-input" />
                    </div>
                    <div class="user-list">
                        <div v-for="user in filteredAssigneeList" :key="user.nickName" class="user-item"
                            @click="toggleAssignee(user)">
                            <div class="user-avatar">
                                {{ user.nickName.charAt(0) }}
                            </div>
                            <div class="user-name">
                                {{ user.nickName }}
                            </div>
                            <el-icon v-if="bugDetail.assignees.includes(user.nickName)" class="check-icon">
                                <Check />
                            </el-icon>
                        </div>
                        <div v-if="filteredAssigneeList.length === 0" class="empty-tip">
                            无匹配结果
                        </div>
                    </div>
                    <div class="dropdown-footer">
                        <el-button type="primary" size="small" class="confirm-btn" @click="updateBugEdit">
                            确定
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 内容区域 -->
        <div class="bug-content">
            <!-- 问题描述 -->
            <div class="content-section">
                <h3 class="section-title">问题现象</h3>
                <div class="section-content" v-html="bugDetail.bugPhenomenon" @click="showImg($event)"></div>
            </div>

            <div class="content-section">
                <h3 class="section-title">复现步骤</h3>
                <div class="section-content" v-html="bugDetail.repeatSteps" @click="showImg($event)"></div>
            </div>

            <div class="content-section">
                <h3 class="section-title">影响范围</h3>
                <div class="section-content" v-html="bugDetail.scope" @click="showImg($event)"></div>
            </div>

            <div class="content-section">
                <h3 class="section-title">期望结果</h3>
                <div class="section-content" v-html="bugDetail.hopeResult" @click="showImg($event)"></div>
            </div>

            <!-- 评论区域 -->
            <div class="comments-section">
                <h3 class="section-title">评论</h3>

                <!-- 评论输入框 -->
                <div class="comment-editor">
                    <div class="editor-avatar">
                        <span>我</span>
                    </div>
                    <div class="editor-main">
                        <textarea v-model="newComment.newCommentMsg" placeholder="写下你的评论..." class="comment-textarea"
                            rows="3"></textarea>
                        <div class="editor-actions">
                            <el-button type="primary" size="small" class="send-btn"
                                :disabled="!newComment.newCommentMsg.trim()" @click="addComment">
                                发送
                            </el-button>
                        </div>
                    </div>
                </div>

                <!-- 评论列表 -->
                <div class="comment-list">
                    <div v-for="(comment, index) in comments" :key="index" class="comment-item">
                        <div class="comment-avatar">
                            {{ comment.createUserName.charAt(0) }}
                        </div>
                        <div class="comment-content">
                            <div class="comment-header">
                                <span class="comment-author">{{ comment.createUserName }}</span>
                                <span class="comment-time">{{ comment.createAt }}</span>
                            </div>
                            <div class="comment-text" v-html="comment.bugMsg" @click="showImg($event)"></div>
                        </div>
                    </div>

                    <div v-if="comments.length === 0" class="empty-comments">
                        暂无评论
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
    FindBugMsgById,
    UpdateBugLevelById,
    UpdateBugStatusById,
    GetRoleUser,
    UpdateBugEditById,
    GetBugMsgById,
    PostAddBugTipsById,
    GetBugStatusList
} from '@/api/newDemands/index'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ArrowDown, Search, Check } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// Bug详情数据
const bugDetail = ref<any>({
    id: 0,
    itemRequirementId: 0,
    bugTitle: '',
    bugStatus: 0,
    bugStatusOrder: 0,
    bugStatusColor: '',
    bugStatusName: '',
    createUserName: '',
    editUserName: [],
    endEditUserName: '',
    bugLevel: 0,
    createTime: '',
    assignees: [],
    bugPhenomenon: '',
    repeatSteps: '',
    scope: '',
    hopeResult: ''
})

// 评论相关
const comments = ref<any[]>([])
const newComment = ref({
    newCommentId: 0,
    newCommentMsg: '',
    bugStatus: 0,
    bugLevel: 0,
})

// 筛选相关
const showPrioritySelect = ref(false)
const showStatusSelect = ref(false)
const showAssigneeSelect = ref(false)
const assigneeSearchKeyword = ref('')
const assigneeList = ref<any[]>([])
const bugStatusList = ref<any[]>([])

// 优先级定义
const PRIORITY_COLORS = [
    { value: 0, label: "全部", bgColor: "#409eff", textColor: "#fff" },
    { value: 1, label: "致命", bgColor: "#ff4d4f", textColor: "#fff" },
    { value: 2, label: "严重", bgColor: "#ffc107", textTextColor: "#fff" },
    { value: 3, label: "一般", bgColor: "#52c41a", textColor: "#fff" },
    { value: 4, label: "建议", bgColor: "#909399", textColor: "#fff" },
]

const PRIORITY_COLORS2 = [
    { value: 1, label: "致命", bgColor: "#ff4d4f", textColor: "#fff" },
    { value: 2, label: "严重", bgColor: "#ffc107", textColor: "#fff" },
    { value: 3, label: "一般", bgColor: "#52c41a", textColor: "#fff" },
    { value: 4, label: "建议", bgColor: "#909399", textColor: "#fff" },
]

// 工具函数
const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

const getPriorityType = (level: number): string => {
    if (level === 1) return 'danger'
    if (level === 2) return 'warning'
    if (level === 3 || level === 4) return 'info'
    return 'default'
}

const getBugStatusType = (status: number): string => {
    if (status === 1) return 'info'
    if (status === 2) return 'warning'
    if (status === 3) return 'success'
    return 'default'
}

const getBugLevelName = (level: number): string => {
    const levelObj = PRIORITY_COLORS.find((p) => p.value === level)
    return levelObj ? levelObj.label : '未知等级'
}

const getBugLevelColor2 = (level: number): string => {
    const levelObj = PRIORITY_COLORS2.find((p) => p.value === level)
    return levelObj ? levelObj.bgColor : '#999'
}

const getBugLevelTextColor2 = (level: number): string => {
    const levelObj = PRIORITY_COLORS2.find((p) => p.value === level)
    return levelObj ? levelObj.textColor : '#000'
}

const getBugStatusName = (status: number) => {
    const statusObj = bugStatusList.value.find((s) => s.bug_status === status)
    return statusObj ? statusObj.bug_status_name : '未知状态'
}

const getBugStatusColor = (status: number) => {
    const statusObj = bugStatusList.value.find((s) => s.bug_status === status)
    return statusObj ? statusObj.bugStatusColor : '#999'
}

const filteredAssigneeList = computed(() => {
    const keyword = assigneeSearchKeyword.value.trim().toLowerCase()
    if (!keyword) return assigneeList.value
    return assigneeList.value.filter((user) =>
        user.nickName.toLowerCase().includes(keyword)
    )
})

// 方法
const toggleAssignee = (user: any) => {
    if (bugDetail.value.assignees.includes(user.nickName)) {
        bugDetail.value.assignees = bugDetail.value.assignees.filter(
            (name: string) => name !== user.nickName
        )
    } else {
        bugDetail.value.assignees.push(user.nickName)
    }
}

const updateBugEdit = async () => {
    try {
        const bugEdits = assigneeList.value
            .filter((user) => bugDetail.value.assignees.includes(user.nickName))
            .map((user) => user.uuid)

        const response = await UpdateBugEditById({
            id: bugDetail.value.id,
            bugEdits: bugEdits,
        })

        if (response.data.code === 200) {
            ElMessage.success('修复人更新成功')
            showAssigneeSelect.value = false
        } else {
            ElMessage.error(response.data.msg)
        }
    } catch (error) {
        ElMessage.error('修复人更新失败')
    }
}

const changePriority = async (bug: any, newLevel: number) => {
    try {
        const response = await UpdateBugLevelById({
            id: bug.id,
            bug_level: newLevel,
        })

        if (response.data.code === 200) {
            bugDetail.value.bugLevel = newLevel
            ElMessage.success('优先级更新成功')
        } else {
            ElMessage.error(response.data.msg)
        }
    } catch (error) {
        ElMessage.error('优先级更新失败')
    } finally {
        showPrioritySelect.value = false
    }
}

const changeStatus = async (bug: any, newStatus: number) => {
    try {
        const response = await UpdateBugStatusById({
            id: bug.id,
            bug_status: newStatus,
        })

        if (response.data.code === 200) {
            bugDetail.value.bugStatus = newStatus
            ElMessage.success('状态更新成功')
        } else {
            ElMessage.error(response.data.msg)
        }
    } catch (error) {
        ElMessage.error('状态更新失败')
    } finally {
        showStatusSelect.value = false
    }
}

const addComment = async () => {
    if (!newComment.value.newCommentMsg.trim()) return

    try {
        const { data } = await PostAddBugTipsById({
            ...newComment.value,
            newCommentId: bugDetail.value.id
        })

        if (data.code === 200) {
            await fetchComments()
            newComment.value.newCommentMsg = ''
            ElMessage.success('评论添加成功')
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        ElMessage.error('评论添加失败')
    }
}

const fetchComments = async () => {
    try {
        const { data } = await GetBugMsgById(bugDetail.value.id)
        if (data.code === 200) {
            comments.value = data.data.map((item: any) => ({
                bugMsg: item.bug_msg,
                createUserName: item.create_user_name,
                createAt: item.createAt,
            }))
        }
    } catch (error) {
        console.error('获取评论失败:', error)
    }
}

const fetchBugStatusList = async () => {
    try {
        const { data } = await GetBugStatusList()
        if (data.code === 200) {
            bugStatusList.value = data.data
        }
    } catch (error) {
        console.error('获取状态列表失败:', error)
    }
}

const fetchAssignees = async () => {
    try {
        const { data } = await GetRoleUser()
        if (data.code === 200) {
            assigneeList.value = data.data
        }
    } catch (error) {
        console.error('获取用户列表失败:', error)
    }
}

const fetchBugDetail = async () => {
    const bugId = route.params.id
    if (!bugId) return

    try {
        const { data } = await FindBugMsgById(bugId)
        if (data.code === 200) {
            bugDetail.value = {
                id: data.data.ID,
                itemRequirementId: data.data.item_requirement_id,
                bugTitle: data.data.bug_title,
                bugStatus: data.data.bug_status,
                bugStatusOrder: data.data.bug_tips ? 1 : 0,
                bugStatusColor: '',
                bugStatusName: getBugStatusName(data.data.bug_status),
                createUserName: data.data.create_user_name,
                editUserName: data.data.edit_user_names.split('|'),
                endEditUserName: data.data.end_edit_user_name,
                bug_msgs: data.data.bug_msgs,
                bugLevel: data.data.bug_level,
                createTime: data.data.createAt,
                assignees: data.data.edit_user_names.split('|'),
                hopeResult: data.data.hopeResult,
                bugPhenomenon: data.data.bugPhenomenon,
                repeatSteps: data.data.repeatSteps,
                scope: data.data.scope,
            }
            newComment.value.bugLevel = data.data.bug_level
            newComment.value.bugStatus = data.data.bug_status
        }
    } catch (error) {
        console.error('获取Bug详情失败:', error)
    }
}

const showImg = (event: MouseEvent) => {
    const target = event.target as HTMLElement
    if (target.tagName === 'IMG') {
        const targetImage = target as HTMLImageElement
        window.open(targetImage.src, '_blank')
    }
}

const goBack = () => {
    router.go(-1)
}

// 初始化
onMounted(async () => {
    await fetchBugDetail()
    await fetchComments()
    await fetchBugStatusList()
    await fetchAssignees()
})
</script>

<style scoped>
.bug-detail-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 16px;
    position: relative;
}

/* 返回按钮 */
.back-button {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 16px;
    color: #409eff;
    font-size: 14px;
    cursor: pointer;
}

.back-button:hover {
    color: #66b1ff;
}

/* 标题区域 */
.bug-title h3 {
    font-size: 1.5rem;
    font-weight: 600;
    margin-bottom: 20px;
    color: #333;
    word-break: break-word;
}

/* 基本信息区域 */
.bug-info {
    background: #f9fafb;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 20px;
}

/* 优先级和状态标签 */
.el-tag {
    padding: 0 10px;
    height: 28px;
    line-height: 28px;
    font-size: 13px;
}

/* 下拉菜单 */
.priority-dropdown,
.status-dropdown {
    position: absolute;
    left: 0;
    top: 100%;
    margin-top: 4px;
    background: white;
    border-radius: 6px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 10;
    min-width: 100px;
    border: 1px solid #ebeef5;
}

.status-dropdown {
    min-width: 140px;
}

.dropdown-item {
    padding: 8px 12px;
    font-size: 13px;
    cursor: pointer;
}

.dropdown-item:hover {
    background-color: #f5f7fa;
}

/* 基本信息网格布局 */
.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 8px 16px;
    margin-bottom: 16px;
}

.info-item {
    display: flex;
    align-items: center;
    font-size: 13px;
}

.info-label {
    color: #606266;
    margin-right: 4px;
}

.info-value {
    color: #303133;
    word-break: break-all;
}

/* 修复人选择器 */
.assignee-container {
    position: relative;
    margin-top: 12px;
}

.assignee-label {
    font-size: 13px;
    color: #606266;
    margin-bottom: 6px;
}

.assignee-selector {
    display: flex;
    align-items: center;
    padding: 6px 12px;
    background: white;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    transition: border-color 0.2s;
}

.assignee-selector:hover {
    border-color: #c0c4cc;
}

.avatar-group {
    display: flex;
    margin-right: 8px;
}

.avatar {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: #409eff;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    margin-left: -8px;
}

.avatar:first-child {
    margin-left: 0;
}

.assignee-names {
    flex: 1;
    font-size: 13px;
    color: #606266;
    display: flex;
    align-items: center;
}

.placeholder {
    color: #c0c4cc;
}

.arrow-icon {
    margin-left: 4px;
    font-size: 12px;
    color: #c0c4cc;
}

/* 修复人下拉框 */
.assignee-dropdown {
    position: absolute;
    left: 0;
    top: 100%;
    width: 100%;
    margin-top: 8px;
    background: white;
    border-radius: 6px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 10;
    border: 1px solid #ebeef5;
    padding: 8px;
}

.search-box {
    position: relative;
    margin-bottom: 8px;
}

.search-icon {
    position: absolute;
    left: 8px;
    top: 50%;
    transform: translateY(-50%);
    color: #c0c4cc;
    font-size: 14px;
}

.search-input {
    width: 100%;
    padding: 8px 8px 8px 30px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    font-size: 13px;
    outline: none;
}

.search-input:focus {
    border-color: #409eff;
}

.user-list {
    max-height: 200px;
    overflow-y: auto;
    margin-bottom: 8px;
}

.user-item {
    display: flex;
    align-items: center;
    padding: 8px;
    border-radius: 4px;
    cursor: pointer;
}

.user-item:hover {
    background-color: #f5f7fa;
}

.user-avatar {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: #409eff;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    margin-right: 8px;
}

.user-name {
    flex: 1;
    font-size: 13px;
    color: #606266;
}

.check-icon {
    color: #409eff;
    font-size: 14px;
}

.empty-tip {
    text-align: center;
    font-size: 13px;
    color: #909399;
    padding: 8px;
}

.dropdown-footer {
    display: flex;
    justify-content: flex-end;
}

.confirm-btn {
    padding: 6px 16px;
}

/* 内容区域 */
.content-section {
    margin-bottom: 24px;
}

.section-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 12px;
    color: #333;
    display: flex;
    align-items: center;
    position: relative;
    padding-left: 12px;
}

.section-title::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background-color: #3b82f6;
    border-radius: 2px;
    margin-right: 10px;
}

.section-content {
    font-size: 14px;
    line-height: 1.6;
    color: #606266;
    word-break: break-word;
}

/* 评论区域 */
.comments-section {
    margin-top: 32px;
    border-top: 1px solid #ebeef5;
    padding-top: 20px;
}

/* 评论编辑器 */
.comment-editor {
    display: flex;
    gap: 12px;
    margin-bottom: 24px;
}

.editor-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: #409eff;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    flex-shrink: 0;
}

.editor-main {
    flex: 1;
}

.comment-textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    font-size: 14px;
    resize: vertical;
    min-height: 80px;
    outline: none;
    transition: border-color 0.2s;
}

.comment-textarea:focus {
    border-color: #409eff;
}

.editor-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 8px;
}

.send-btn {
    padding: 6px 16px;
}

/* 评论列表 */
.comment-list {
    margin-top: 16px;
}

.comment-item {
    display: flex;
    gap: 12px;
    padding: 12px 0;
    border-bottom: 1px solid #f0f2f5;
}

.comment-item:last-child {
    border-bottom: none;
}

.comment-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: #909399;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    flex-shrink: 0;
}

.comment-content {
    flex: 1;
}

.comment-header {
    display: flex;
    align-items: center;
    margin-bottom: 6px;
}

.comment-author {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    margin-right: 8px;
}

.comment-time {
    font-size: 12px;
    color: #909399;
}

.comment-text {
    font-size: 14px;
    line-height: 1.6;
    color: #606266;
    word-break: break-word;
}

.empty-comments {
    text-align: center;
    color: #909399;
    font-size: 13px;
    padding: 16px 0;
}

/* 移动端适配 */
@media (max-width: 768px) {
    .bug-detail-container {
        padding: 12px;
    }

    .bug-title h3 {
        font-size: 1.3rem;
        margin-bottom: 16px;
    }

    .bug-info {
        padding: 12px;
    }

    .info-grid {
        grid-template-columns: 1fr;
    }

    .section-title {
        font-size: 1rem;
    }

    .section-content {
        font-size: 13px;
    }

    .comment-editor,
    .comment-item {
        gap: 8px;
    }

    .editor-avatar,
    .comment-avatar {
        width: 32px;
        height: 32px;
        font-size: 13px;
    }

    .comment-author {
        font-size: 13px;
    }

    .comment-text {
        font-size: 13px;
    }

    .comment-textarea {
        font-size: 13px;
        min-height: 70px;
    }
}

@media (max-width: 480px) {
    .bug-title h3 {
        font-size: 1.2rem;
    }

    .priority-dropdown,
    .status-dropdown {
        min-width: 0;
        width: 100%;
    }

    .assignee-dropdown {
        width: calc(100vw - 32px);
        left: -8px;
    }
}
</style>